<template>
  <div class="gva-table-box">
    <div class="gva-btn-list search-form" style="padding-top: 80px">
      <el-form ref="formRef" :model="OrderInfo" style="width: 100%">
        <el-row :gutter="20" class="flex">
          <el-col :span="5">
            <el-form-item label="系统单号" prop="global_order_no">
              <el-input
                clearable
                v-model="OrderInfo.global_order_no"
                placeholder="系统单号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态" prop="status">
              <el-select clearable v-model="OrderInfo.status" placeholder="选择状态">
                <el-option value="1" label="待审核" />
                <el-option value="2" label="待配货" />
                <el-option value="3" label="待发货" />
                <el-option value="4" label="已发货" />
                <el-option value="5" label="已完成" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否超时发货" prop="is_overdue">
              <el-select clearable v-model="OrderInfo.is_overdue" placeholder="是否超时">
                <el-option value="1" label="是" />
                <el-option value="0" label="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="仓库" prop="store_name">
              <el-select clearable v-model="OrderInfo.store_name" placeholder="仓库">
                <el-option value="Hangzhou" label="Hangzhou" />
                <el-option value="Shenzhen" label="Shenzhen" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否追踪" prop="istrack">
              <el-select clearable v-model="OrderInfo.istrack" placeholder="是否追踪">
                <el-option value="1" label="是" />
                <el-option value="0" label="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item>
              <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="OrderInfo.CreateStartTime"
                type="date"
                placeholder="发货开始时间"
                :size="size"
              />
              <div class="mr-5" />
              <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="OrderInfo.CreateEndTime"
                type="date"
                placeholder="发货结束时间"
                :size="size"
              />
              <el-button
                type="primary"
                icon="Search"
                class="action"
                style="margin-left: 20px"
                @click="getsearch"
                >搜索</el-button
              >
              <el-button class="action reset" @click="resetForm()">重置搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <div>
        <div>
          <el-button class="action" type="primary" @click="exportToExcel"
            >导出本页物流信息</el-button
          >
          <el-button class="action" type="primary" @click="exportallToExcel"
            >导出所有物流</el-button
          >
        </div>
        <el-table
          :data="dataList"
          row-key="ID"
          :row-class-name="tableRowClassName"
          style="height: 480px"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          v-model:selection="multipleSelection"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" label="序" min-width="75">
            <template #default="scope">
              <span>{{ (page - 1) * pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="系统单号"
            min-width="200"
            prop="global_order_no"
          />
          <el-table-column
            align="center"
            label="平台名称"
            min-width="200"
            prop="platform_code"
          >
          </el-table-column>
          <el-table-column align="center" label="平台状态" prop="platform_status">
            <template #default="scope">
              {{ scope.row.platform_status != "0" ? scope.row.platform_status : "" }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="币种" prop="amount_currency" />
          <el-table-column align="center" label="店铺" min-width="200" prop="username" />
          <el-table-column
            align="center"
            label="仓库"
            min-width="200"
            prop="store_name"
          />
          <el-table-column align="center" label="备注" prop="remark" />
          <el-table-column
            align="center"
            label="物流商"
            min-width="200"
            prop="logistics_provider_name"
          >
            <template #default="scope">
              {{
                scope.row.logistics_provider_name != "0"
                  ? scope.row.logistics_provider_name
                  : ""
              }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="运单号"
            min-width="200"
            prop="waybill_no"
          >
            <template #default="scope">
              <span
                style="color: #005bf5; cursor: pointer"
                @click="handleModal(scope.row.waybill_no)"
                >{{ scope.row.waybill_no != "0" ? scope.row.waybill_no : "" }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="物流状态"
            min-width="200"
            prop="trackstatus"
          >
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="light"
                :content="scope.row.tracksstr"
                raw-content
                placement="right"
              >
                <span>{{ scope.row.trackstatus }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="status">
            <template #default="scope">
              {{ handleStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="处理状态" prop="state">
            <template #default="scope">
              {{handleState(scope.row.state)}}
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            label="会员付款时间"
            min-width="200"
            prop="fx_payment_time"
          >
            <template #default="scope">
              {{ gettime(scope.row.fx_payment_time) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="进入待发货时间"
            min-width="200"
            prop="distributiontime"
          >
            <template #default="scope">
              {{ gettime(scope.row.distributiontime) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="发货时间"
            min-width="200"
            prop="global_delivery_time"
          >
            <template #default="scope">
              {{ gettime(scope.row.global_delivery_time) }}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed="right"
            label="发货时限"
            min-width="200"
            prop="global_latest_ship_time"
          >
            <template #default="scope">
              <div :class="[scope.row.is_overdue == 1 ? 'red' : '']">
                {{ gettime(scope.row.global_latest_ship_time) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            min-width="180"
            prop="Status"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                class="action-btn"
                @click="remarkmodal(scope.row)"
                >备注</el-button
              >
              <el-button
                v-if="scope.row.is_overdue == 1"
                type="success"
                size="small"
                class="action-btn"
                @click="solved(scope.row.id)"
                >标记处理</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 40]"
            layout="prev, pager, next, jumper, total, sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-dialog v-model="trackVisible" width="600px" center>
      <iframe :src="iframeUrl" style="width: 100%; height: 520px"> </iframe>
    </el-dialog>
    <el-dialog v-model="remarkVisible" title="备注" width="400">
      <el-form
        ref="remarkForm"
        :model="Remark"
        label-width="auto"
        style="max-width: 400px"
      >
        <el-form-item label="备注：" prop="Remark">
          <el-input type="textarea" :rows="2" v-model="Remark" placeholder="订单备注" />
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button
            type="primary"
            @click="remarkOrder"
            style="margin: 0 auto; padding: 5px 8px"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import {
  getSumoolOrderList,
  setorderremark,
  setsolved,
  getSumoolerrOrderList,
  getSumoolallOrderList,
} from "@/api/orderlimit";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
defineOptions({
  name: "sumoolorderd",
});
const route = useRoute();

const router = useRouter();
const loading = ref(false);

// 获取商品列表
const dataList = ref([]);
const wareList = ref([]);
const page = ref(1);
const pageSize = ref(10);
const orderId = ref(0);
const remarkVisible = ref(false);
const Remark = ref("");
const total = ref(0);
const iframeUrl = ref("");
const trackVisible = ref(false);
const query = route.query;
const multipleSelection = ref([]);
const orderIds = ref([]);

const OrderInfo = reactive({
  global_order_no: "",
  is_overdue: query.is_overdue ? query.is_overdue : "",
  status: query.status ? query.status : "",
  store_name: "",
});
const handleModal = (waybill_no) => {
  iframeUrl.value = "https://www.track123.com/iframe/home?trackNos=" + waybill_no;
  trackVisible.value = !trackVisible.value;
};
const remarkmodal = (row) => {
  orderId.value = row.id;
  Remark.value = row.Remark;
  remarkVisible.value = !remarkVisible.value;
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  orderIds.value = [];
  val.forEach((element) => {
    orderIds.value.push(element.id);
  });
};
const remarkOrder = () => {
  let request = {
    id: orderId.value,
    Remark: Remark.value,
  };
  setorderremark(request).then((res) => {
    if (res.errcode == 0) {
      ElMessage({
        message: "操作成功",
        type: "success",
      });
      getOrderData(OrderInfo);
      remarkVisible.value = !remarkVisible.value;
    }
  });
};
const exportToExcel = () => {
  // 假设你有一个表格的数据
  const data = ref([
    // { name: 'Alice', email: 'alice@example.com' },
    // { name: 'Bob', email: 'bob@example.com' }
  ]);
  dataList.value.forEach((element) => {
    let id = element.id;
    if (orderIds.value.length > 0) {
      if (orderIds.value.includes(id)) {
        let trackarr = JSON.parse(element.tracks);
        trackarr.forEach((content, index) => {
          let obj = {
            订单号: index == 0 ? element.global_order_no : "",
            物流单号: index == 0 ? element.waybill_no : "",
            物流状态: index == 0 ? element.trackstatus : "",
            物流时间: content.eventTime,
            物流信息: content.eventDetail,
          };
          data.value.push(obj);
        });
      }
    } else {
      let trackarr = JSON.parse(element.tracks);
      trackarr.forEach((content, index) => {
        let obj = {
          订单号: index == 0 ? element.global_order_no : "",
          物流单号: index == 0 ? element.waybill_no : "",
          物流状态: index == 0 ? element.trackstatus : "",
          物流时间: content.eventTime,
          物流信息: content.eventDetail,
        };
        data.value.push(obj);
      });
    }
  });
  function replaceAll(string, search, replace) {
    return string.split(search).join(replace);
  }
  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(data.value);

  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成Excel文件
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

  // 字符串转ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }

  // 保存文件
  saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "data.xlsx");
};
const exportallToExcel = () => {
  loading.value = true;

  getSumoolallOrderList(OrderInfo).then((res) => {
    if (res.errcode == 0) {
      loading.value = false;

      let dataerrList = res.content;
      const data1 = ref([]);
      dataerrList.forEach((element) => {
        let trackarr = JSON.parse(element.tracks);
        if (trackarr) {
          trackarr.forEach((content, index) => {
            let obj = {
              订单号: index == 0 ? element.global_order_no : "",
              发货时间: index == 0 ? gettime(element.global_delivery_time) : "",
              物流商: index == 0 ? element.logistics_provider_name : "",
              物流单号: index == 0 ? element.waybill_no : "",
              物流状态: index == 0 ? element.trackstatus : "",
              物流时间: content.eventTime,
              物流信息: content.eventDetail,
            };
            data1.value.push(obj);
          });
        } else {
          let obj = {
            订单号: element.global_order_no,
            发货时间: gettime(element.global_delivery_time),
            物流商: element.logistics_provider_name,
            物流单号: element.waybill_no,
            物流状态: element.trackstatus,
            物流时间: "",
            物流信息: "",
          };
          data1.value.push(obj);
        }
      });
      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(data1.value);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "data.xlsx");
    }
  });
};
const exporterrToExcel = () => {
  getSumoolerrOrderList().then((res) => {
    if (res.errcode == 0) {
      let dataerrList = res.content;
      const data1 = ref([]);
      dataerrList.forEach((element) => {
        let trackarr = JSON.parse(element.tracks);
        if (trackarr) {
          trackarr.forEach((content, index) => {
            let obj = {
              订单号: index == 0 ? element.global_order_no : "",
              发货时间: index == 0 ? gettime(element.global_delivery_time) : "",
              物流商: index == 0 ? element.logistics_provider_name : "",
              物流单号: index == 0 ? element.waybill_no : "",
              物流状态: index == 0 ? element.trackstatus : "",
              物流时间: content.eventTime,
              物流信息: content.eventDetail,
            };
            data1.value.push(obj);
          });
        } else {
          let obj = {
            订单号: element.global_order_no,
            发货时间: gettime(element.global_delivery_time),
            物流商: element.logistics_provider_name,
            物流单号: element.waybill_no,
            物流状态: element.trackstatus,
            物流时间: "",
            物流信息: "",
          };
          data1.value.push(obj);
        }
      });
      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(data1.value);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "data.xlsx");
    }
  });
};
const solved = async (id) => {
  ElMessageBox.confirm(`确定处理完成吗？`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await setsolved({
      id: id,
    });
    if (res.errcode === 0) {
      ElMessage({
        type: "success",
        message: "操作成功",
      });
      getOrderData(OrderInfo);
    }
  });
};
const handleState = (Status) => {
  switch (Status) {
    case "0":
      return "";
      break;
    case "1":
      return "未处理";
      break;
    case "2":
      return "已处理";
      break;
    default:
      return "";
  }
};
const handleStatus = (Status) => {
  switch (Status) {
    case "0":
      return "未付款";
      break;
    case "1":
      return "待审核";
      break;
    case "2":
      return "待配货";
      break;
    case "3":
      return "待发货";
      break;
    case "4":
      return "已发货";
      break;
    case "5":
      return "已完成";
      break;
    default:
      return "";
  }
};
const gettime = (shijianchuo) => {
  if (!Number(shijianchuo)) {
    return "- -";
  }
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(Number(shijianchuo * 1000));
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return (
    y + "-" + add0(m) + "-" + add0(d) + " " + add0(h) + ":" + add0(mm) + ":" + add0(s)
  );
};
function add0(m) {
  return m < 10 ? "0" + m : m;
}

const getOrderData = async (requestdata) => {
  requestdata.PageIndex = page.value;
  requestdata.PageSize = pageSize.value;
  loading.value = true;
  getSumoolOrderList(requestdata).then((res) => {
    loading.value = false;

    if (res.errcode == 0) {
      dataList.value = res.content;
      dataList.value.forEach((element) => {
        let tracksstr = "";
        if (element.tracks) {
          let trackarr = JSON.parse(element.tracks);
          trackarr.forEach((content) => {
            tracksstr += content.eventTime + ":" + content.eventDetail + "<br />";
          });
        }
        element["tracksstr"] = tracksstr;
      });
      total.value = Number(res.totalRecords);
    }
  });
};
const getwarehouse = (wid) => {
  if (wareList[wid]) {
    return wareList[wid];
  } else {
    return "";
  }
};
getOrderData(OrderInfo);

const getsearch = async () => {
  page.value = 1;
  getOrderData(OrderInfo);
};

const handleCurrentChange = (num) => {
  page.value = num;
  getOrderData(OrderInfo);
};

const handleSizeChange = (num) => {
  pageSize.value = num;
  getOrderData(OrderInfo);
};
const formRef = ref();
const resetForm = () => {
  // OrderInfo.global_order_no = '';
  formRef.value.resetFields();
  getOrderData(OrderInfo);
};
const tableRowClassName = ({ row, rowIndex }) => {
  // 通过rowIndex判断奇偶行，添加不同的类名
  if (rowIndex % 2 === 0) {
    return "even-row";
  } else {
    return "odd-row";
  }
};
</script>

<style lang="scss" scoped>
iframe {
  border: none;
}
.balanceTitle {
  font-size: 20px;
  margin-bottom: 20px;
}
.activetitle {
  color: red;
  margin-left: 12px;
}
.red {
  color: red;
}
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.gva-table-box {
  margin: 20px;
}

:deep(.el-input__inner) {
  font-size: 12px !important;
  color: rgba(0, 0, 0, 0.85) !important;
}

:deep(.el-select__wrapper) {
  font-size: 12px !important;

  .el-select__selected-item {
    font-size: 12px !important;
  }
}

.logo-img {
  width: 46px;
}
</style>

<style lang="scss">
:deep(.el-form-item) {
  align-content: center;
}
</style>
